package texture;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class FallbackResourceManager implements ResourceManager {
	protected final List<ResourcePack> resourcePacks = new ArrayList<>();
	private MetadataSerializer frmMetadataSerializer;

	public FallbackResourceManager(MetadataSerializer par1MetadataSerializer) {
		this.frmMetadataSerializer = par1MetadataSerializer;
	}

	public void addResourcePack(ResourcePack par1ResourcePack) {
		this.resourcePacks.add(par1ResourcePack);
	}

	@Override
	public Resource getResource(ResourceLocation par1ResourceLocation) throws IOException {
		ResourcePack resourcepack = null;
		ResourceLocation resourcelocation1 = getLocationMcmeta(par1ResourceLocation);

		for (int i = this.resourcePacks.size() - 1; i >= 0; --i) {
			ResourcePack resourcepack1 = (ResourcePack) this.resourcePacks.get(i);

			if (resourcepack == null && resourcepack1.resourceExists(resourcelocation1)) {
				resourcepack = resourcepack1;
			}

			if (resourcepack1.resourceExists(par1ResourceLocation)) {
				InputStream inputstream = null;

				if (resourcepack != null) {
					inputstream = resourcepack.getInputStream(resourcelocation1);
				}

				return new SimpleResource(par1ResourceLocation, resourcepack1.getInputStream(par1ResourceLocation), inputstream, this.frmMetadataSerializer);
			}
		}

		throw new FileNotFoundException(par1ResourceLocation.toString());
	}

	private ResourceLocation getLocationMcmeta(ResourceLocation par1ResourceLocation) {
		 return new ResourceLocation(par1ResourceLocation.getResourceDomain(), par1ResourceLocation.getResourcePath() + ".mcmeta");
	}

}
